﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Validation;

namespace Chen.IdentityServer4
{
    /// <summary>
    /// 短信验证码登录
    /// </summary>
    public class SmsGrantValidator : IExtensionGrantValidator
    {
        public string GrantType => "smsgrant";

        public Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var phone = context.Request.Raw["phone"];
            var smsCode = context.Request.Raw["smscode"];
            //var shopId = context.Request.Raw["shopid"];

            if (string.IsNullOrWhiteSpace(phone) || string.IsNullOrWhiteSpace(smsCode))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "参数错误");
                return Task.CompletedTask;
            }
            Regex regex = new Regex(@"\d{3}-\d{8}|\d{4}-\{7,8}");
            if (!regex.IsMatch(phone))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "手机号格式错误");
                return Task.CompletedTask;
            }

            // 登录系统
            //var loginRes = _accountLogic.LoginBySms(phone, smsCode).Result;
            //if (!loginRes.IsSucceed || loginRes.Data <= 0)
            //{
            //    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "登录失败:" + loginRes.Message);
            //    return Task.CompletedTask;
            //}
            //var accountInfo = _accountLogic.QueryById(loginRes.Data).Result;
            //if (accountInfo == null || accountInfo.AccountId <= 0)
            //{
            //    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "账户信息查询失败");
            //    return Task.CompletedTask;
            //}
            //List<Claim> claims = new List<Claim>()
            //{
            //    new Claim("accountid", loginRes.Data.ToString()) ,
            //    //new Claim("phone", accountInfo.Phone) ,
            //    new Claim("isptaccount", accountInfo.IsPtAccount?"1":"0") ,
            //};
            //context.Result = new GrantValidationResult(loginRes.Data.ToString(), GrantType, claims: claims);
            return Task.CompletedTask;
        }
    }
}
